package com.shbatitstwo.transaction.jdbc;

import com.shbatitstwo.transaction.Transaction;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Auther: sh
 * @Version 1.0
 * @Description: JDBC事务管理器
 */
public class JdbcTransaction implements Transaction {


    // 数据源
    private DataSource dataSource;
    // 是否自动提交  true: 自动提交  false: 非自动提交
    private boolean autoCommit;
    // 数据库连接对象
    private Connection connection;


    public JdbcTransaction(DataSource dataSource, boolean autoCommit) {
        this.dataSource = dataSource;
        this.autoCommit = autoCommit;
    }


    @Override
    public void commit() {
        try {
            connection.commit();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void rollback() {
        try {
            connection.rollback();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void close() {
        try {
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void openConnection() {
        try {
            if (connection == null) {
                connection = dataSource.getConnection();
                if (autoCommit) {
                    connection.setAutoCommit(true);
                } else {
                    connection.setAutoCommit(false);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 获取数据库连接对象
    @Override
    public Connection getConnection() {
        return connection;
    }
}

